from django import forms
from django.contrib.auth.forms import UsernameField
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import datetime #for checking renewal date range.
from .models import BookInstance, BookReview, FavoriteGroup, Profile

class RegisterForm(forms.Form):
    username = UsernameField(
        label=_("username"),
        widget=forms.TextInput(attrs={"autofocus": True})
    )
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
    )
    error_messages = {
        "invalid_login": _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        "inactive": _("This account is inactive."),
    }

class RenewBookForm(forms.Form):
    renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")

    def clean_renewal_date(self):
        data = self.cleaned_data['renewal_date']

        #Check date is not in past.
        if data < datetime.date.today():
            raise ValidationError(_('Invalid date - renewal in past'))

        #Check date is in range +4 weeks from today.
        if data > datetime.date.today() + datetime.timedelta(weeks=4):
            raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))

        # Remember to always return the cleaned data.
        return data

class RatingForm(forms.Form):
    rating = forms.IntegerField(min_value=1, max_value=5, widget=forms.RadioSelect(choices=[(i, str(i)) for i in range(1, 6)]))

class ReviewForm(forms.ModelForm):
    class Meta:
        model = BookReview
        fields = ['content']
        labels = {'content': _('Review')}
        widgets = {
            'content': forms.Textarea(attrs={'rows': 4, 'placeholder': _('Write your review here...')})
        }

class FavoriteGroupForm(forms.ModelForm):
    color = forms.CharField(widget=forms.TextInput(attrs={'type': 'color'}))
    class Meta:
        model = FavoriteGroup
        fields = ['name', 'color']

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['bio', 'avatar']
        widgets = {
            'bio': forms.Textarea(attrs={'rows': 3, 'placeholder': _('Tell us about yourself...')}),
        }
